package com.jxaummd.aquaculture.ui.fragment.first;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.jxaummd.aquaculture.R;
import com.jxaummd.aquaculture.adapter.FuncationAdapter;
import com.jxaummd.aquaculture.base.BaseMainFragment;
import com.jxaummd.aquaculture.entity.Funcation;
import com.jxaummd.aquaculture.entity.event.MqttMessageEvent;
import com.jxaummd.aquaculture.entity.event.MqttMessageReciveEvent;
import com.jxaummd.aquaculture.listener.OnItemClickListener;
import com.jxaummd.aquaculture.ui.fragment.MainFragment;
import com.jxaummd.aquaculture.ui.fragment.first.fun.ControlFragment;
import com.jxaummd.aquaculture.ui.fragment.first.fun.InfoFragment;
import com.jxaummd.aquaculture.ui.fragment.first.fun.RangeChooseFragment;

import org.eclipse.paho.client.mqttv3.internal.wire.MqttReceivedMessage;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by YoKeyword on 16/6/30.
 */
public class FirstTabFragment extends BaseMainFragment{
    private RecyclerView mRecy;
    private FuncationAdapter mAdapter;
    private Button mOpenButton = null;
    private boolean[] status={false,false,false,false,false,false,false};
    private TextView mTextTemp ;
    private TextView mTextPh ;
    private TextView mTextOxygen ;
    private TextView mTextWork ;

    private TextView mTexthint ;



    public static FirstTabFragment newInstance() {
        Bundle args = new Bundle();
        FirstTabFragment fragment = new FirstTabFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        EventBus.getDefault().register(this);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mRecy = view.findViewById(R.id.fragment_device_function);
        mOpenButton = view.findViewById(R.id.fragment_device_open_lock);

        mTextTemp = view.findViewById(R.id.home_page1_temp);
        mTextOxygen = view.findViewById(R.id.home_page1_oxygen);
        mTextPh = view.findViewById(R.id.home_page1_ph);
        mTextWork = view.findViewById(R.id.home_page1_work);

        mTexthint = view.findViewById(R.id.home_page_view2_text);
    }

    @Override
    public void onLazyInitView(@Nullable final Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        mRecy.setLayoutManager(new GridLayoutManager(_mActivity, 3));
        mAdapter = new FuncationAdapter(_mActivity);
        mRecy.setAdapter(mAdapter);
        mOpenButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mOpenButton.getText().equals("启动设备")){
                    mOpenButton.setBackgroundResource(R.drawable.bg_button_enable);
                    mOpenButton.setText("关闭设备");
                    EventBus.getDefault().post(new MqttMessageEvent("#o|20#","/esp8266/sub840d8ea472b5"));
                }else {
                    mOpenButton.setBackgroundResource(R.drawable.bg_button_disable);
                    mOpenButton.setText("启动设备");
                    EventBus.getDefault().post(new MqttMessageEvent("#c|20#","/esp8266/sub840d8ea472b5"));
                }
            }
        });


        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position, View view, RecyclerView.ViewHolder vh) {
                int v;
                if(status[position]){
                    v = 0;
                    ((ImageView)view.findViewById(R.id.item_device_fun_image)).setColorFilter(getResources().getColor(R.color.greay));
                }else {
                    v =90;
                    ((ImageView)view.findViewById(R.id.item_device_fun_image)).setColorFilter(getResources().getColor(R.color.colorAccent));
                }
                status[position]=!status[position];
                switch (position){
                    case 0:
                        EventBus.getDefault().post(new MqttMessageEvent("#f|"+v+"#","/esp8266/sub840d8ea472b5"));
                        break;
                    case 1:
                        EventBus.getDefault().post(new MqttMessageEvent("#s|"+v+"#","/esp8266/sub840d8ea472b5"));
                        break;
                    case 2:
                        start(RangeChooseFragment.newInstance("投食量"));
                        break;
                    case 3:
                        start(RangeChooseFragment.newInstance("撒药量"));
                        break;
                    case 4:

                        start(ControlFragment.newInstance());
                        break;
                }
            }
        });
        List<Funcation> chatList = initDatas();
        mAdapter.setDatas(chatList);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(MqttMessageReciveEvent event) {
        String msg = event.getMessage();
        JSONObject jsonObject = JSONObject.parseObject(msg);
        if(jsonObject!=null){
            mTextTemp.setText(jsonObject.getFloat("temp")+"°c");
            double temp = jsonObject.getFloat("temp");

            String oxygen = jsonObject.getFloat("oxygen")*10+"";

            mTextOxygen.setText(oxygen.subSequence(0,oxygen.indexOf('.')+2)+"mg/L");


            double vph = jsonObject.getFloat("ph")*(-5.8)+16.72;
            String ph = vph+"";
            if(vph<6.5){
               mTexthint.setText("检测到当前水质中PH值偏碱性（PH<6.5），建议进行水质调控~");
               mTexthint.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       start((InfoFragment.newInstance("偏酸性（PH＜6.5）水质的调控。\n" +
                               "未受外界酸性物质污染的水体如PH值偏低，一般与水体缺氧，有机物质偏多，水质过肥有关，因此水体PH值偏低是水质不良的表现，其调控方法如下：\n" +
                               "用生石灰全池泼洒提高PH值，一般用20ppm的生石灰可提高PH值0.5左右，生石灰还可补充水中钙离子，提高水的缓冲力，起到杀菌防病作用。\n" +
                               "使用藻类生长素，加速培育浮游植物，消耗水体过多CO2，提高池水的PH值。\n" +
                               "施用微生态制剂和水质改良剂改善水质。\n" +
                               "用氢氧化钠充分稀释后全池泼洒。")));
                   }
               });

            }else if(vph>8.5){
                mTexthint.setText("检测到当前水质中PH值偏酸性（PH>8.5），建议进行水质调控~");
                mTexthint.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        start((InfoFragment.newInstance("偏碱（PH＞8.5）性水质的调控\n" +
                                "渔池水PH值过高时清塘时不能用生石灰而应改用漂白粉清塘，生产过程中，当PH值过高时应采用以下几种方法进行调节：\n" +
                                "可每亩用醋酸500ml或用盐酸400ml充分稀释后全池泼洒。\n" +
                                "可适当排出底部老水（一般15-20cm），然后再向池塘注入新水至原来的水位，在2-3d后使用微生态制剂调节水质。\n" +
                                "泼洒沸石粉、滑石粉或其它化学制剂如二氯化钙(CaCl2)、磷酸二氢钠(NaH2PO3)等以降低pH值。\n" +
                                "养殖水体中浮游生物过多时，可用明矾0.5-1kg/亩或灭藻灵或硫酸铜等来控制浮游生物大量繁殖以减少光合作用强烈时引起PH值进一步升高，但在高温季度应慎用硫酸铜，在使用上述化学剂制后应使用增氧机增氧。")));
                    }
                });

            }else if(temp<16||temp>30){
                mTexthint.setText("检测到当前水温不太适宜，请多多注意小龙虾的生长~");
                mTexthint.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
            }else if(jsonObject.getFloat("oxygen")*10<3){
                mTexthint.setText("检测到当前水温不太适宜，请多多注意小龙虾的生长~");
                mTexthint.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        start(InfoFragment.newInstance("溶解氧对于水生生物生长及发育及其重要，如果池塘呈现缺氧状态会造成小龙虾发育、脱壳变缓，严重直接造成死亡。一般要求小龙虾养殖池塘水体溶解氧含量不低于5mg/L。在小龙虾养殖中后期及天气突变时极易完成池塘缺氧，需要养殖户做好巡塘管理。如果发现有小龙虾侧身爬伏于水草上就表明池塘处于缺氧状态，需要及时开启增氧机或泼洒增氧药物。"));

                    }
                });
            }else {
                mTexthint.setText("当前水质正常，请不用担心~");
            }

            mTextPh.setText(ph.subSequence(0,ph.indexOf('.')+2));
            mTextWork.setText("正在工作");
        }

    }

    private List<Funcation> initDatas() {
        List<Funcation> list = new ArrayList<>();
        String[] name = new String[]{"投食", "撒药", "投食量", "撒药量", "手动控制", "定时设置"};
        Integer[] icon = new Integer[]{R.drawable.ic_imag_01, R.drawable.ic_imag_02, R.drawable.ic_imag_3, R.drawable.ic_imag_04, R.drawable.ic_imag_05, R.drawable.ic_imag_06,R.drawable.ic_imag_07};
        for (int i = 0; i < 6; i++) {
            Funcation chat = new Funcation();
            chat.setName(name[i]);
            chat.setImageId(icon[i]);
            list.add(chat);
        }
        return list;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
